<?php
/**
 * Created by PhpStorm.
 * User: aiChenK
 * Date: 2019-02-12
 * Time: 13:23
 */

namespace Services\Msg\Core\Task;

use Helpers\Main;
use Helpers\Page;
use Helpers\Tool;
use Services\Login\Login;
use Services\Msg\Models\Task;

class Finder
{

    private $enum = [
        'isHandle' => [
            0 => '<i class="fa fa-ban" style="color: #23b7e5;"></i>',
            1 => '<i class="fa fa-check" style="color: #2baab1;"></i>'
        ],
        'level' => [
            Creator::LEVEL_NORMAL    => '<div class="grid-cell-text-bg-gray">一般</div>',
            Creator::LEVEL_IMPORTANT => '<div class="grid-cell-text-bg-yellow">重要</div>',
            Creator::LEVEL_EMERGENCY => '<div class="grid-cell-text-bg-red">紧急</div>',
        ],
    ];

    /**
     * 获取任务列表
     *
     * @param $page
     * @param $size
     * @param array $params
     * @param array $option
     * @return array
     *
     * create by ck 20190213
     */
    public function list($page, $size, $params = [], $option = [])
    {
        //处理条件
        $condition = [];
        $isScrap   = Tool::getValue($params, 'isScrap');
        if (is_numeric($isScrap)) {
            $condition[] = "task.isScrap = '{$isScrap}'";
        }
        $isHandle = Tool::getValue($params, 'isHandle');
        if (is_numeric($isHandle)) {
            $condition[] = "task.isHandle = '{$isHandle}'";
        }
        $condition = implode(' AND ', $condition);
        $condition and $condition = 'AND ' . $condition;

        $userId = Login::getId();
        $sql    = "SELECT
                target.id,
                task.id AS taskId,
                task.title,
                task.url,
                task.`level`,
                task.viewMode,
                target.isRead,
                task.isHandle,
                task.handlerId,
                task.handleAt,
                task.isScrap,
                task.createAt,
                task.createBy
            FROM `XHRemind_TaskTarget` AS target
            LEFT JOIN `XHRemind_Task` AS task ON target.taskId = task.id
            WHERE
                target.isDel = 0
            AND task.isDel = 0
            AND target.targetId = {$userId}
            {$condition}
            ORDER BY task.id DESC";
        $data   = Page::runSqlPage($sql, $page, $size);

        //处理显示信息
        Tool::runTimestamp($data['rows'], ['createAt' => 'createAt', 'handleAt' => 'handleAt']);
        if (Tool::getValue($option, 'enum', true) !== false) {
            foreach ($data['rows'] as &$row) {
                $style = [];
                if (!$row['isHandle']) {
                    $style[] = 'font-weight: bold;';
                }
                if ($row['isScrap']) {
                    $style[] = 'text-decoration: line-through;';
                }
                $style        = implode(' ', $style);
                $row['title'] = "<div style='{$style}'>{$row['title']}</div>";
            }
            unset($row);
            Tool::runEnum($data['rows'], $this->enum);
        }
        if (Tool::getValue($option, 'user', true) !== false) {
            Main::runUserName($data['rows'], ['createBy' => 'createBy', 'handlerId' => 'handlerId']);
        }
        return ['total' => $data['total'], 'rows' => $data['rows']];
    }

    /**
     * 获取未处理任务列表
     *
     * @param int $num
     * @return array
     *
     * create by ck 20190213
     */
    public function unhandledList(int $num = 5)
    {
        return $this->list(
            1,
            $num,
            ['isScrap' => 0, 'isHandle' => 0],
            ['enum' => false, 'user' => false]
        );
    }

    /**
     * 根据id获取任务详情
     *
     * @param int $id
     * @return array
     * @throws \Exception
     *
     * create by ck 20190214
     */
    public function detail(int $id)
    {
        $info = Task::findFirst([
            'columns'    => ['id', 'title', 'url', 'viewMode', 'level', 'isScrap', 'isHandle'],
            'conditions' => 'isDel = 0 AND id = :id:',
            'bind'       => ['id' => $id]
        ]);
        if (!$info) {
            throw new \Exception('该任务不存在或已被删除');
        }
        if ($info->isScrap) {
            throw new \Exception('该任务已失效');
        }
        return $info->toArray();
    }
}
